import { Tooltip, Tour } from "antd";
import "./index.scss";
import {
  FormEvent,
  FormEventHandler,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { isSameElement } from "../../utils";
import InputChat from "./components/input-chat";
import MsgWrapper from "./components/msg-wrapper";
const emojis =
  "😀,😃,😄,😁,😆,😅,😂,🤣,😊,😇,🙂,🙃,😉,😌,😍,😘,😗,😙,😚,😋,😛,😝,😜,🤪,🤨,🧐,🤓,😎,🤩,😏,😒,😞,😔,😟,😕,🙁,😣,😖,😫,😩,😢,😭,😮,💨,😤,😠,😡,🤬,🤯,😳,😱,😨,😰,😥,😓,🤗,🤔,🤭,🤫,🤥,😶,🌫️,😐,😑,😬,🙄,😯,😦,😧,😮,😲,😴,🤤,😪,😵,💫,🤐,🤢,🤮,🤧,😷,🤒,🤕,🤑,🤠,😈,👿,👹,👺,🤡,💩,👻,💀,👽,👾,🤖,🎃,😺,😸,😹,😻,😼,😽,🙀,😿,😾,🐶";
function Index() {
  const emojiList = useMemo(() => emojis.split(","), []);
  console.log(emojiList);
  const [selectAtVisible, setSelectAtVisible] = useState(false);
  const atRootRef = useRef<HTMLDivElement | null>(null);
  // 最后@符号的位置信息
  const selectionRef = useRef<any>(null);
  // 缓存range (用户点击input输入框后，然后点击emoji图标，点击后range就会变为点击的元素，所以要把input的焦点位置缓存起来)
  const rangeRef = useRef<any>(null);
  const inputRef = useRef<HTMLDivElement | null>(null);
  const handleChatInput: FormEventHandler<HTMLDivElement> = (
    v: FormEvent<HTMLDivElement>
  ) => {
    // 获取光标位置
    const selection = window.getSelection();
    selectionRef.current = selection;
    if (!selection?.focusNode) return false;
    // 解决换行生成的的br标签产生的问题
    if (
      !selection.focusNode ||
      !selection.focusNode.nodeValue ||
      selection.focusOffset === 0
    )
      return false;
    const range = selection.getRangeAt(0);
    rangeRef.current = range;
    console.log(rangeRef.current);
    const lastWord = selection.focusNode.nodeValue[selection.focusOffset - 1];
    if (lastWord !== "@") return false;
    // selectionRef.current = selection
    // 获取选中区域的范围 获取光标的范围
    // 返回一个包含当前选区内容的区域对象。 该参数指定需要被处理的子集编号（从零开始计数）。如果该数值被错误的赋予了大于或等于 rangeCount 结果的数字，将会产生错误。

    // 获取选中区域的边界 获取当前光标的坐标点 这个方法里面都有getBoundingClientRect()
    const rect = range.getBoundingClientRect();
    // console.log(rect)
    atRootRef.current?.style.setProperty("left", rect.left + "px");
    atRootRef.current?.style.setProperty("top", rect.top + "px");
    setSelectAtVisible(true);
  };

  // const handleChatFocus: FormEventHandler<HTMLDivElement> = (v: FormEvent<HTMLDivElement>) => {
  //     // 缓存range
  //     console.log('handleChatFocus', v)
  //     // 获取光标位置
  //     // const selection = window.getSelection();
  //     // if (!selection) return false
  //     //  // 解决换行生成的的br标签产生的问题
  //     //  if (!selection.focusNode || !selection.focusNode.nodeValue || selection.focusOffset=== 0) return false
  //     // const range = selection.getRangeAt(0)
  //     // rangeRef.current = range
  // }

  const handleSelectAt = (v: any) => {
    if (!selectionRef.current) return false;
    // 将@符号替换为<span>@XXX</span>

    // 创建元素
    const atEle = document.createElement("span");
    // 为了删除的时候能将span整体给删除
    atEle.setAttribute("contentEditable", "false");
    atEle.innerHTML = `@${v}`;
    atEle.classList.add("at-wrapper");
    // 获取光标在那个节点位置上
    const range = selectionRef.current.getRangeAt(0);
    range.insertNode(atEle);

    if (range.startContainer) {
      // 判断当前节点是否是文本节点text
      if (range.startContainer.nodeType === 3) {
        if (range.startContainer.nodeValue === "@") {
          // 一个text节点只有一个@元素时，直接将其删除(如果不删除会出现许多空的text节点)
          range.startContainer.parentElement.removeChild(range.startContainer);
        } else {
          // 将最后@符号删除
          range.startContainer.nodeValue =
            range.startContainer.nodeValue.replace(/@$/, "");
        }
      } else {
        console.log("不是文本节点，暂不处理");
      }
    }

    // 将光标设置到新增加的@xx之后
    range.setStartAfter(atEle);
    // range.setEnd(atEle, 1);
    // range.collapse(true);
    // 获取焦点
    inputRef.current?.focus();

    // const parentElement = selectionRef.current.focusNode.parentElement
    // selectionRef.current.getRangeAt(0).insertNode(atEle)
    // console.log(selectionRef.current.getRangeAt(0))
    // @ts-ignore
    // eslint-disable-next-line @typescript-eslint/no-unused-expressions
    // parentElement.appendChild(atEle)
    // 先将@符号移除
    // if (selectionRef.current.focusNode.nodeType === 3) {
    //     if (selectionRef.current.focusNode.nodeValue === '@') { // 一个text节点只有一个@元素时，直接将其删除
    //         parentElement.removeChild(selectionRef.current.focusNode)
    //     } else {
    //         selectionRef.current.focusNode.nodeValue = selectionRef.current.focusNode.nodeValue.replace(/@$/, '')
    //     }
    // } else {
    //     console.log('不是3', selectionRef.current.focusNode)
    // }

    // const index = Array.from(parentElement.childNodes).findIndex(node => node === atEle)
    // console.log('index', index, parentElement.childNodes)
    // let range = document.createRange();
    // range.setStart(parentElement, 2); // 将光标移动到第5个字符的位置
    // range.setStartAfter(atEle.childNodes[0]);
    // range.setEnd(atEle, 1);
    // range.collapse(true);
    // parentElement.focus()
    setSelectAtVisible(false);
  };

  const handleAtOpenChange = (open: boolean) => {
    console.log("open", open);
  };

  const handleSelectEmoji = (emojiValue: string) => {
    if (!inputRef.current) return false;
    if (!selectionRef.current) {
      // input输入框为空
      inputRef.current.innerHTML = inputRef.current.innerHTML + emojiValue;
    } else {
      console.log(rangeRef.current);

      if (rangeRef.current && rangeRef.current.endContainer) {
        // rangeRef.current.endContainer.nodeValue += emojiValue
        // 当在输入框中选中内容，选中的内容是同一个节点
        if (rangeRef.current.startContainer === rangeRef.current.endContainer) {
          if (rangeRef.current.startContainer.nodeType === 3) {
            const strList = rangeRef.current.startContainer.nodeValue.split("");
            const { startOffset, endOffset, startContainer, endContainer } =
              rangeRef.current;
            //      1 -                 5
            // ['1', '2', '3', '4', '5', '6']
            strList.splice(startOffset, endOffset - startOffset, emojiValue);
            startContainer.nodeValue = strList.join("");
            // 设置光标位置
            const range = selectionRef.current.getRangeAt(0);
            // range.setStartAfter(startContainer);

            range.setStart(startContainer, startOffset + emojiValue.length);
            range.setEnd(startContainer, startOffset + emojiValue.length);
            // range.setEnd(endContainer, endOffset + emojiValue.length)
            inputRef.current?.focus();
          } else {
            // 元素节点
            console.log(
              rangeRef.current.commonAncestorContainer.childNodes,
              rangeRef.current.endOffset
            );
            // rangeRef.current.commonAncestorContainer
            const textNode = document.createTextNode(emojiValue);
            if (
              rangeRef.current.endOffset ===
              rangeRef.current.commonAncestorContainer.childNodes.length
            ) {
              rangeRef.current.commonAncestorContainer.appendChild(textNode);
            } else {
              rangeRef.current.commonAncestorContainer.insertBefore(
                textNode,
                rangeRef.current.commonAncestorContainer.childNodes[
                  rangeRef.current.endOffset
                ]
              );
            }
          }
        } else {
          // 选中的元素是多个元素，那么就需要将选中的元素给删除掉
          if (!rangeRef.current.commonAncestorContainer) return false;
          let isCanDelete = false; // 是否可以删除
          const range = selectionRef.current.getRangeAt(0);
          const { startOffset, endOffset, startContainer, endContainer } =
            rangeRef.current;
          Array.from(
            rangeRef.current.commonAncestorContainer.childNodes
          ).forEach((one) => {
            if (one === rangeRef.current.endContainer) {
              isCanDelete = false;
            }
            if (isCanDelete) {
              rangeRef.current.commonAncestorContainer.removeChild(one);
            } else if (one === rangeRef.current.startContainer) {
              isCanDelete = true;
            }
          });
          if (rangeRef.current.startContainer.nodeType === 3) {
            // 删除start节点
            const strStartList =
              rangeRef.current.startContainer.nodeValue.split("");
            strStartList.splice(rangeRef.current.startOffset);
            strStartList.push(emojiValue);
            rangeRef.current.startContainer.nodeValue = strStartList.join("");

            if (rangeRef.current.endContainer.nodeType === 3) {
              // 删除end节点
              const strEndList =
                rangeRef.current.endContainer.nodeValue.split("");
              strEndList.splice(0, rangeRef.current.endOffset);
              rangeRef.current.endContainer.nodeValue = strEndList.join("");
            }

            range.setStart(startContainer, startOffset + emojiValue.length);
            range.setEnd(startContainer, startOffset + emojiValue.length);
            // range.setEnd(endContainer, endOffset + emojiValue.length)
            inputRef.current?.focus();
            // 删除
          } else if (rangeRef.current.endContainer.nodeType === 3) {
            if (rangeRef.current.startContainer.nodeType === 3) {
              const strStartList =
                rangeRef.current.startContainer.nodeValue.split("");
              strStartList.splice(rangeRef.current.startOffset);
              rangeRef.current.startContainer.nodeValue = strStartList.join("");
            }

            const strEndList =
              rangeRef.current.endContainer.nodeValue.split("");
            strEndList.splice(0, rangeRef.current.endOffset);
            strEndList.unshift(emojiValue);
            rangeRef.current.endContainer.nodeValue = strEndList.join("");

            range.setStart(endContainer, emojiValue.length);
            range.setEnd(endContainer, emojiValue.length);
            // range.setEnd(endContainer, endOffset + emojiValue.length)
            inputRef.current?.focus();
          } else {
          }
        }
      }
    }
  };

  return (
    <div className="home bg-gray-500 h-screen flex flex-col">
      <div className=" bg-main-2 w-4/5 h-4/5 m-auto rounded-2xl flex overflow-hidden">
        <aside className="side-toolbar w-[80px] bg-main-2 box-border px-4 py-5">
          <div className="avatar bg-red-400 aspect-square rounded-full"></div>
          <div className="tool-icons ">
            <div className="tool-icons-item mt-4">
              <a
                // href="javascript:void(0)"
                className=" rounded-lg aspect-square rounded-full flex items-center justify-center cursor-pointer hover:bg-main-1 text-white hover:text-blue-500 duration-300"
              >
                <i className="michat icon-group "></i>
              </a>
            </div>
            <div className="tool-icons-item mt-4">
              <a
                // href="javascript:void(0)"
                className=" rounded-lg aspect-square rounded-full flex items-center justify-center cursor-pointer hover:bg-main-1 text-white hover:text-blue-500 duration-300"
              >
                1
              </a>
            </div>
          </div>
        </aside>

        <section className="flex-1 min-w-0 box-border py-5 pr-5 flex ">
          <div className="chat-wrapper bg-main-1 h-full flex-1 min-w-0 rounded-xl overflow-hidden flex flex-col">
            <div className="bg-[#5B5E69] h-[47px] flex items-center px-5">
              <span className="text-white text-base">测试对接群</span>
            </div>
            <div className="flex-1 min-w-0 overflow-y-auto overflow-x-hidden px-5">
              {/* 滚动内容区域 */}
              <div className="">
                {new Array(10).fill(1).map((_one, index) => {
                  return (
                    <MsgWrapper key={index} />
                  );
                })}
              </div>
            </div>
            <InputChat></InputChat>
            {/* <div className="bg-[#424656]  flex items-center px-5 py-1" >
                        <div className="tools-menu flex items-center mr-3">
                            <div className="tools-item w-[26px] aspect-square rounded-md hover:bg-gray-800 flex flex-col cursor-pointer duration-300">
                                <i className="voice-ani michat icon-voice block m-auto !text-lg text-white"></i>
                            </div>
                        </div>
                        <InputChat setAtRootStyle={setAtRootStyle}></InputChat>
                        <div  ref={inputRef}  onInput={handleChatInput} spellCheck="false" data-placeholder="你的骚话吧~" className="input-chat w-full text-white rounded-md px-3 py-1 duration-300 outline-none border border-opacity-0 focus:border-opacity-100 border-blue-500 max-h-[150px] overflow-y-auto" contentEditable="true"></div>
                        <div className="tools-menu flex items-center ml-3" >
                        <Tooltip
                            trigger="click"
                            placement="top"
                            rootClassName="tools-menu-tooltip"
                            color="#272a37"
                            arrow
                            title={
                                <div className='w-[364px] max-h-[300px] overflow-y-auto select-none'>
                                    <ul className='flex flex-wrap'>
                                        {emojiList.map((one, index) => <li 
                                            key={index}
                                            className=' rounded-md hover:bg-[#3b3e4d] text-xl cursor-pointer duration-300 w-[28px] aspect-square flex justify-center items-center'
                                            onClick={() => handleSelectEmoji(one)}
                                        >{one}</li>)}
                                    </ul>
                                </div>
                            }
                        >
                            <div  className="tools-item w-[26px] aspect-square rounded-md hover:bg-gray-800 flex flex-col cursor-pointer duration-300">
                                <i className="michatcolor icon-happy1 block m-auto !text-lg"></i>
                            </div>
                         </Tooltip>
                           

                            <div className="tools-item w-[26px] aspect-square rounded-md hover:bg-gray-800 flex flex-col cursor-pointer duration-300">
                                <i className="michatcolor icon-at block m-auto !text-lg"></i>
                            </div>

                            <div className="tools-item w-[26px] aspect-square rounded-md hover:bg-gray-800 flex flex-col cursor-pointer duration-300">
                                <i className="michatcolor icon-tupian block m-auto !text-lg"></i>
                            </div>

                            <div className="tools-item w-[26px] aspect-square rounded-md hover:bg-gray-800 flex flex-col cursor-pointer duration-300">
                                <i className="michatcolor icon-wenjianjia2 block m-auto !text-lg"></i>
                            </div>
                        </div>
                    </div> */}
          </div>
        </section>
      </div>
    </div>
  );
}

export default Index;
